<script setup lang="ts">
import { ElMessage } from "element-plus"
import { computed, ref, watch } from "vue"
import { useApplicationTeacherStore } from "@/pinia/stores/application-teacher"

interface Props {
  visible: boolean
  applicationId: number
}

const props = defineProps<Props>()
const emit = defineEmits<{
  "update:visible": [value: boolean]
}>()

const store = useApplicationTeacherStore()
const loading = ref(false)
const drawerVisible = ref(props.visible)

watch(
  () => props.visible,
  (newVal) => {
    drawerVisible.value = newVal
  }
)

watch(
  () => drawerVisible.value,
  (newVal) => {
    emit("update:visible", newVal)
  }
)

// 监听applicationId变化，获取详情
watch(
  () => props.applicationId,
  async (newId) => {
    if (newId && props.visible) {
      loading.value = true
      const detail = await store.fetchApplicationDetail(newId)
      loading.value = false

      // 只在报名待审核（状态码48）时请求AI评判
      if (detail && detail.applicationStatus === 48) {
        setTimeout(() => {
          store.fetchAiEvaluation(newId)
        }, 100)
      } else {
        // 其他状态清除AI评估结果
        store.aiEvaluation = null
        store.evaluationError = null
      }
    }
  },
  { immediate: true }
)

// 查看简历
function handleViewResume(resumeUrl: string) {
  if (resumeUrl) {
    window.open(resumeUrl, "_blank")
  }
}

// 审核弹窗状态管理
const reviewDialogVisible = ref(false)
const reviewForm = ref({
  applicationId: 0,
  applicationStatus: 48, // 默认状态
  reviewRemark: "",
  operationType: "" // 通过或拒绝
})

// 统一处理所有审核操作
function handleInterviewReview(status: number) {
  let reviewRemark = ""

  if (status === 62 && store.aiEvaluation) {
    const aiReason = store.aiEvaluation.reason?.join("；") || ""
    const aiSuggestions = store.aiEvaluation.improvementSuggestions?.join("；") || ""

    // 构建自动备注内容
    let autoRemark = ""
    if (aiReason) {
      autoRemark += `【未通过原因】：${aiReason}`
    }
    if (aiSuggestions) {
      autoRemark += autoRemark ? "\n" : ""
      autoRemark += `【改进建议】：${aiSuggestions}`
    }

    reviewRemark = autoRemark
  }

  reviewForm.value = {
    applicationId: props.applicationId,
    applicationStatus: status, // 49: 报名通过, 50: 面试通过, 51: 面试拒绝, 62: 报名拒绝
    reviewRemark,
    operationType: [49, 50].includes(status) ? "通过" : "拒绝"
  }
  reviewDialogVisible.value = true
}

// 计算弹窗标题
const getReviewDialogTitle = computed(() => {
  const operation = reviewForm.value.operationType
  const stage = [49, 62].includes(reviewForm.value.applicationStatus) ? "报名" : "面试"
  return `确认${operation}${stage}审核`
})

// 计算当前操作名称
const getCurrentOperationName = computed(() => {
  const operation = reviewForm.value.operationType
  const stage = [49, 62].includes(reviewForm.value.applicationStatus) ? "报名" : "面试"
  return `${stage}${operation}`
})

// 提交审核
async function handleSubmitReview() {
  // 对于拒绝操作，必须填写理由
  if (reviewForm.value.operationType === "拒绝" && !reviewForm.value.reviewRemark.trim()) {
    ElMessage.warning("请填写拒绝原因")
    return
  }

  const success = await store.reviewApplication({
    applicationId: reviewForm.value.applicationId,
    applicationStatus: reviewForm.value.applicationStatus,
    reviewRemark: reviewForm.value.reviewRemark,
    reviewTeacherId: 0
  })

  if (success) {
    reviewDialogVisible.value = false
  }
}

// 根据分数获取颜色
function getScoreColor(score: number) {
  if (score >= 80) return "#67c23a"
  if (score >= 60) return "#e6a23c"
  return "#f56c6c"
}
</script>

<template>
  <vxe-drawer
    v-model="drawerVisible"
    title="申请详情"
    width="1600"
    height="100%"
    mask-closable
  >
    <div v-if="loading" class="loading-content">
      <div class="loading-spinner-wrapper">
        <div class="loading-spinner">
          <div class="spinner" />
          <p class="loading-text">
            加载中...
          </p>
        </div>
      </div>
    </div>
    <div v-else-if="store.currentApplicationDetail" class="three-column-layout">
      <!-- 第一列：简历预览 -->
      <div class="column resume-column">
        <div class="column-header">
          <h3>简历预览</h3>
        </div>
        <div class="resume-content">
          <div v-if="store.currentApplicationDetail.resumeUrl" class="resume-preview">
            <iframe
              :src="store.currentApplicationDetail.resumeUrl"
              title="简历预览"
              class="resume-iframe"
              @error="handleViewResume(store.currentApplicationDetail.resumeUrl)"
            />
          </div>
          <div v-else class="no-resume">
            <el-empty description="暂无简历" />
          </div>
        </div>
      </div>

      <!-- 第二列：申请详情 -->
      <div class="column detail-column">
        <div class="column-header">
          <h3>申请详情</h3>
        </div>
        <div class="detail-scroll">
          <el-card>
            <template #header>
              <div class="card-header">
                <span>基本信息</span>
              </div>
            </template>
            <el-descriptions :column="1" border>
              <el-descriptions-item label="学生姓名">
                {{ store.currentApplicationDetail.realName }}
              </el-descriptions-item>
              <el-descriptions-item label="政治面貌">
                {{ store.currentApplicationDetail.politicalStatus }}
              </el-descriptions-item>
              <el-descriptions-item label="性别">
                {{ store.currentApplicationDetail.gender === 0 ? '男' : '女' }}
              </el-descriptions-item>
              <el-descriptions-item label="组织名称">
                {{ store.currentApplicationDetail.orgName }}
              </el-descriptions-item>
              <el-descriptions-item label="组织路径">
                {{ store.currentApplicationDetail.orgPath }}
              </el-descriptions-item>
              <el-descriptions-item label="联系电话">
                {{ store.currentApplicationDetail.phone }}
              </el-descriptions-item>
              <el-descriptions-item label="邮箱">
                {{ store.currentApplicationDetail.email }}
              </el-descriptions-item>
              <el-descriptions-item label="申请状态">
                <el-tag
                  :type="store.currentApplicationDetail.applicationStatus === 1 ? 'success'
                    : store.currentApplicationDetail.applicationStatus === 2 ? 'danger'
                      : store.currentApplicationDetail.applicationStatus === 3 ? 'primary'
                        : store.currentApplicationDetail.applicationStatus === 4 ? 'success'
                          : store.currentApplicationDetail.applicationStatus === 5 ? 'danger' : 'info'"
                >
                  {{ store.currentApplicationDetail.applicationStatusName || store.currentApplicationDetail.applicationStatus }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="提交时间">
                {{ store.currentApplicationDetail.submitTime }}
              </el-descriptions-item>
            </el-descriptions>
          </el-card>

          <!-- 语言能力 -->
          <el-card v-if="store.currentApplicationDetail.languages && store.currentApplicationDetail.languages.length > 0" class="mt-4">
            <template #header>
              <div class="card-header">
                <span>语言能力</span>
              </div>
            </template>
            <div class="table-wrapper">
              <el-table :data="store.currentApplicationDetail.languages" stripe border size="small" fit style="width: 100%;">
                <el-table-column prop="language" label="语言" width="auto" />
                <el-table-column prop="level" label="等级" width="auto" />
                <el-table-column prop="score" label="分数" width="auto" />
              </el-table>
            </div>
          </el-card>

          <!-- 技能信息 -->
          <el-card v-if="store.currentApplicationDetail.skills && store.currentApplicationDetail.skills.length > 0" class="mt-4">
            <template #header>
              <div class="card-header">
                <span>技能信息</span>
              </div>
            </template>
            <div class="table-wrapper">
              <el-table :data="store.currentApplicationDetail.skills" stripe border size="small" fit style="width: 100%;">
                <el-table-column prop="skillName" label="技能名称" width="100" />
                <el-table-column prop="proficiency" label="熟练度" width="80" />
                <el-table-column prop="description" label="描述" width="auto" />
              </el-table>
            </div>
          </el-card>

          <!-- 实习经历 -->
          <el-card v-if="store.currentApplicationDetail.internExperiences && store.currentApplicationDetail.internExperiences.length > 0" class="mt-4">
            <template #header>
              <div class="card-header">
                <span>实习经历</span>
              </div>
            </template>
            <div class="table-wrapper">
              <el-table :data="store.currentApplicationDetail.internExperiences" stripe border size="small" fit style="width: 100%;">
                <el-table-column prop="company" label="公司名称" width="120" />
                <el-table-column prop="position" label="职位" width="100" />
                <el-table-column prop="startDate" label="开始日期" width="100" />
                <el-table-column prop="endDate" label="结束日期" width="100" />
                <el-table-column prop="content" label="实习内容" width="auto" />
              </el-table>
            </div>
          </el-card>

          <!-- 获奖信息 -->
          <el-card v-if="store.currentApplicationDetail.awards && store.currentApplicationDetail.awards.length > 0" class="mt-4">
            <template #header>
              <div class="card-header">
                <span>获奖信息</span>
              </div>
            </template>
            <div class="table-wrapper">
              <el-table :data="store.currentApplicationDetail.awards" stripe border size="small" fit style="width: 100%;">
                <el-table-column prop="name" label="奖项名称" width="auto" />
                <el-table-column prop="issuer" label="颁发机构" width="150" />
                <el-table-column prop="getDate" label="获得日期" width="120">
                  <template #default="scope">
                    {{ scope.row.getDate || '-' }}
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-card>

          <!-- 其他信息 -->
          <el-card v-if="store.currentApplicationDetail.otherInfo" class="mt-4">
            <template #header>
              <div class="card-header">
                <span>其他信息</span>
              </div>
            </template>
            <div class="other-info">
              {{ store.currentApplicationDetail.otherInfo }}
            </div>
          </el-card>
        </div>
      </div>

      <!-- 第三列：职位需求与审核操作 -->
      <div class="column action-column">
        <div class="column-header">
          <h3>职位需求与审核</h3>
        </div>
        <div class="action-scroll">
          <!-- 职位需求 -->
          <el-card class="position-detail">
            <template #header>
              <div class="card-header">
                <span>职位需求</span>
              </div>
            </template>
            <div v-if="store.positionDetail" class="position-info">
              <el-descriptions :column="1" border>
                <el-descriptions-item label="职位名称">
                  {{ store.positionDetail.positionName || '-' }}
                </el-descriptions-item>
                <el-descriptions-item label="职位描述">
                  {{ store.positionDetail.positionDesc || '-' }}
                </el-descriptions-item>
                <el-descriptions-item label="技能要求">
                  {{ store.positionDetail.positionRequire || '-' }}
                </el-descriptions-item>
                <el-descriptions-item label="其他要求">
                  {{ '-' }}
                </el-descriptions-item>
              </el-descriptions>
            </div>
            <div v-else>
              <el-empty description="暂无职位信息" />
            </div>
          </el-card>

          <!-- AI意见 - 仅在报名待审核状态显示 -->
          <el-card v-if="store.currentApplicationDetail?.applicationStatus === 48" class="mt-4 ai-opinion">
            <template #header>
              <div class="card-header">
                <span>AI匹配意见</span>
                <el-tag v-if="store.evaluationLoading" size="small" type="info">
                  评估中
                </el-tag>
              </div>
            </template>
            <div v-if="store.evaluationLoading" class="text-center py-6">
              <div class="loading-spinner">
                <div class="spinner" />
              </div>
              <p class="mt-3 text-gray-500">
                AI正在分析简历与职位匹配度，预计需要10秒左右...
              </p>
              <p class="mt-1 text-sm text-gray-400">
                该过程不会影响页面其他内容的浏览
              </p>
            </div>
            <div v-else-if="store.aiEvaluation" class="evaluation-content">
              <!-- 推荐状态 -->
              <div class="evaluation-section">
                <div class="section-label">
                  推荐状态：
                </div>
                <el-tag :type="store.aiEvaluation.isRecommended === 'true' ? 'success' : 'danger'" size="large">
                  {{ store.aiEvaluation.isRecommended === 'true' ? '推荐' : '不推荐' }}
                </el-tag>
              </div>

              <!-- 匹配分数 -->
              <div class="evaluation-section">
                <div class="section-label">
                  匹配分数：
                </div>
                <div class="score-display">
                  {{ store.aiEvaluation.matchScore }}/100
                </div>
                <div class="score-progress">
                  <el-progress
                    :percentage="store.aiEvaluation.matchScore"
                    :color="getScoreColor(store.aiEvaluation.matchScore)"
                    :format="() => ''"
                  />
                </div>
              </div>

              <!-- 评估原因 -->
              <div class="evaluation-section">
                <div class="section-label">
                  评估原因：
                </div>
                <ul class="reason-list">
                  <li v-for="(reason, index) in store.aiEvaluation.reason" :key="index">
                    {{ reason }}
                  </li>
                </ul>
              </div>

              <!-- 改进建议 -->
              <div class="evaluation-section">
                <div class="section-label">
                  改进建议：
                </div>
                <ul class="suggestion-list">
                  <li v-for="(suggestion, index) in store.aiEvaluation.improvementSuggestions" :key="index">
                    {{ suggestion }}
                  </li>
                </ul>
              </div>
            </div>
            <div v-else-if="store.evaluationError" class="error-content text-center py-6">
              <el-icon class="text-danger" size="40">
                <WarningFilled />
              </el-icon>
              <p class="mt-3 text-danger">
                AI评估失败
              </p>
              <p class="mt-1 text-sm text-gray-500">
                {{ store.evaluationError }}
              </p>
              <el-button
                type="primary"
                size="small"
                class="mt-3"
                @click="store.fetchAiEvaluation(props.applicationId)"
              >
                重试
              </el-button>
            </div>
            <div v-else class="empty-content text-center py-6">
              <el-empty description="暂无AI评估结果" :image-size="60" />
              <el-button
                type="primary"
                size="small"
                class="mt-3"
                @click="store.fetchAiEvaluation(props.applicationId)"
              >
                获取AI评估
              </el-button>
            </div>
          </el-card>

          <!-- 审核操作按钮 -->
          <div class="review-actions mt-4">
            <!-- 待审核状态：显示通过/拒绝按钮 -->
            <div v-if="store.currentApplicationDetail.applicationStatus === 48">
              <el-button type="success" @click="handleInterviewReview(49)" size="large" class="w-full mb-2">
                报名通过
              </el-button>
              <el-button type="danger" @click="handleInterviewReview(62)" size="large" class="w-full" style="margin-left: 0px;">
                报名未通过
              </el-button>
            </div>

            <!-- 已通过初审状态：显示面试审核按钮 -->
            <div v-else-if="store.currentApplicationDetail.applicationStatus === 49">
              <el-button type="primary" @click="handleInterviewReview(50)" size="large" class="w-full mb-2">
                面试通过
              </el-button>
              <el-button type="danger" @click="handleInterviewReview(51)" size="large" class="w-full" style="margin-left: 0px;">
                面试未通过
              </el-button>
            </div>

            <!-- 已完成审核状态：只显示状态 -->
            <div v-else-if="[50, 51, 62].includes(store.currentApplicationDetail.applicationStatus)" class="review-status-display">
              <el-tag
                :type="store.currentApplicationDetail.applicationStatus === 50 ? 'success' : 'danger'"
                size="large"
                class="w-full justify-center"
              >
                {{ store.currentApplicationDetail.applicationStatus === 50 ? '面试通过'
                  : store.currentApplicationDetail.applicationStatus === 51 ? '面试拒绝' : '申请拒绝' }}
              </el-tag>
            </div>
          </div>

          <!-- 审核记录 -->
          <el-card v-if="store.currentApplicationDetail.reviewRemark" class="mt-4">
            <template #header>
              <div class="card-header">
                <span>审核备注</span>
              </div>
            </template>
            <div class="review-remark">
              {{ store.currentApplicationDetail.reviewRemark || '-' }}
            </div>
          </el-card>
        </div>
      </div>
    </div>
    <div v-else class="empty-content">
      <el-empty description="暂无数据" />
    </div>
  </vxe-drawer>

  <!-- 审核确认弹窗 -->
  <el-dialog
    v-model="reviewDialogVisible"
    :title="getReviewDialogTitle"
    width="500px"
    :z-index="10004"
  >
    <el-form :model="reviewForm" label-width="80px">
      <el-form-item label="审核结果">
        <el-tag :type="reviewForm.operationType === '通过' ? 'success' : 'danger'">
          {{ getCurrentOperationName }}
        </el-tag>
        <input type="hidden" v-model="reviewForm.applicationStatus">
      </el-form-item>
      <el-form-item
        label="审核备注"
        prop="reviewRemark"
      >
        <el-input
          v-model="reviewForm.reviewRemark"
          type="textarea"
          :rows="4"
          :placeholder="reviewForm.operationType === '通过' ? '请输入通过备注（可选）' : '请输入拒绝原因（必填）'"
        />
        <div v-if="reviewForm.operationType === '拒绝'" class="form-hint">
          拒绝原因必填，请详细说明理由
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="reviewDialogVisible = false">
        取消
      </el-button>
      <el-button
        type="primary"
        @click="handleSubmitReview"
        :loading="store.reviewLoading"
      >
        {{ reviewForm.operationType === '通过' ? '确认通过' : '确认拒绝' }}
      </el-button>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
.three-column-layout {
  display: flex;
  height: calc(100% - 20px);
  gap: 16px;
  padding: 0 10px;
}

.column {
  flex: 1;
  display: flex;
  flex-direction: column;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #fff;
}

.column-header {
  padding: 12px 16px;
  border-bottom: 1px solid #ebeef5;
  background-color: #f5f7fa;
  h3 {
    margin: 0;
    font-size: 16px;
    font-weight: 500;
  }
}

.resume-column {
  flex: 1.5;
}

.detail-column {
  flex: 1.2;
}

.action-column {
  flex: 1;
}

.resume-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.resume-preview {
  flex: 1;
  overflow: hidden;
  position: relative;
}

.resume-iframe {
  width: 100%;
  height: 100%;
  border: none;
}

.no-resume {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.detail-scroll,
.action-scroll {
  flex: 1;
  overflow-y: auto;
  padding: 12px;
}

.card-header {
  font-size: 14px;
  font-weight: 500;
}

.other-info,
.review-remark,
.opinion-content,
.evaluation-content {
  padding: 10px;
  line-height: 1.6;
  background-color: #f9f9f9;
  border-radius: 4px;
  word-break: break-word;
}

.evaluation-section {
  margin-bottom: 16px;
}

.section-label {
  font-weight: 500;
  margin-bottom: 8px;
  color: #606266;
}

.score-display {
  font-size: 18px;
  font-weight: 600;
  color: #409eff;
}

.reason-list,
.suggestion-list {
  padding-left: 20px;
  margin: 0;
}

.reason-list li,
.suggestion-list li {
  margin-bottom: 4px;
  color: #606266;
}

.reason-list li:last-child,
.suggestion-list li:last-child {
  margin-bottom: 0;
}

.position-info,
.ai-opinion {
  min-height: 150px;
}

.review-actions {
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.review-status-display .el-tag {
  display: block;
  text-align: center;
}

.form-hint {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.loading-content,
.empty-content {
  height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgba(255, 255, 255, 0.8);
}

.loading-spinner-wrapper {
  text-align: center;
}

.loading-spinner {
  display: inline-block;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 3px solid #f3f3f3;
  border-top: 3px solid #409eff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 10px;
}

.loading-text {
  color: #606266;
  font-size: 14px;
  margin: 0;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

/* AI评估相关样式 */
.ai-opinion {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .score-display {
    font-size: 24px;
    font-weight: bold;
    margin: 8px 0;
  }

  .score-progress {
    margin-top: 4px;
  }

  .evaluation-section {
    margin-bottom: 16px;
  }

  .section-label {
    font-weight: 500;
    margin-bottom: 8px;
    color: #606266;
  }

  .reason-list,
  .suggestion-list {
    padding-left: 20px;
    margin: 0;

    li {
      margin-bottom: 4px;
      color: #606266;
    }
  }

  .error-content,
  .empty-content {
    padding: 30px 0;
  }
}

.text-gray-500 {
  color: #909399;
}

/* 表格包装器，防止表格溢出 */
.table-wrapper {
  overflow-x: auto;
  width: 100%;
}

/* 调整表格样式以适应窄列 */
.el-table {
  font-size: 13px;
  width: 100%;
  table-layout: fixed; /* 固定表格布局，防止自动扩展列 */
}

.el-table__header th,
.el-table__body td {
  padding: 8px;
  height: 40px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 确保表格不会出现多余的列 */
:deep(.el-table__header-wrapper),
:deep(.el-table__body-wrapper) {
  overflow-x: hidden;
}

:deep(.el-table__header-wrapper) {
  overflow: hidden;
}

/* 确保drawer内容不被遮挡 */
:deep(.vxe-drawer--inner) {
  display: flex;
  flex-direction: column;
}

:deep(.vxe-drawer--body) {
  flex: 1;
  overflow: hidden;
}
</style>
